package com.example.bookdemo.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;

import java.security.Key;
import java.util.Date;
import java.util.Map;

@Slf4j
public class JWTUtil {
    //设定令牌有效时间为30分钟
    private static long expiration = 30*60*1000;
    private static String secretString = "sr3kSWSu8/c/75/nMkeEkYRlN0zQVIO+79d3F3CriLk=";
    private static Key key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(secretString));
    
    /**  
     * 生成令牌 
     * @param claims
     * @return
     */  
    public static String getJWT(Map<String,Object> claims){
        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(new Date(System.currentTimeMillis() + expiration))
                .signWith(key)
                .compact();
    }
    
    /**  
     * 校验令牌 
     * @param token  
     * @return  
     */
    public static Claims verify(String token){
        JwtParser build = Jwts.parserBuilder().setSigningKey(key).build();

        Claims claims = null;
        try {
            claims = build.parseClaimsJws(token).getBody();
        }catch (ExpiredJwtException e){
            log.error("token过期, 校验失败, token:"+ token);
        }catch (Exception e){
            log.error("token校验失败, token:"+ token);
        }

        return claims;
    }

    public static Integer getUserToken(String token){
        Claims claims = verify(token);
        System.out.println(claims);
        Assert.notNull(claims,"token不合法");
        Integer userId = (Integer) claims.get("id");
        return userId;
    }
}
